package com.bkgy.component;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bkgy.modular.calsidata.dao.TbFaltMapper;
import com.bkgy.modular.datacollect_bx.bean.*;
import com.bkgy.modular.datacollect_bx.dao.JColdPdo622Dao;
import com.bkgy.modular.qms.service.impl.QmsServiceImpl;
import com.bkgy.controller.tbbxrecord.dao.TbBxFileSaveDao;
import com.bkgy.controller.tbbxrecord.entity.TbBxFileSave;
import com.bkgy.modular.tbdsjdatacollect.dao.TbDsjDataCollectDao;
import com.bkgy.modular.tbdsjrawcheckc642.service.TbDsjRawcheckC642Service;
import com.bkgy.util.PdoUtils;
import com.bkgy.util.PojoUtils;
import com.bkgy.util.SDKUtils;
import com.bkgy.util.SFtpUtils;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;


@Component
@Slf4j
public class Consumer {

    @Autowired
    private SFtpUtils sFtpUtils;

    @Value("${sftp_host_621}")
    String host621;

    @Value("${sftp_host_622}")
    String host;

    @Value("${sftp_host_642}")
    String host642;

    @Value("${sftp_host_653}")
    String host653;
    @Autowired
    private PdoUtils pdoUtils;
    @Resource
    private SDKUtils sdkUtilscs;
    @Resource
    private QmsServiceImpl qmsService;
    @Resource
    private PojoUtils pojoUtils;

    @Resource
    private TbFaltMapper tbFaltMappercs;
    @Resource
    private MongoTemplate mongoTemplate;
    @Resource
    private JColdPdo622Dao jColdPdo622Daocs;
    @Resource
    private TbBxFileSaveDao tbBxFileSaveDao;

    @Resource
    private TbDsjRawcheckC642Service tbDsjRawcheckC642Service;
    @Resource
    private TbDsjDataCollectDao tbDsjDataCollectDaocs;

    public static String transform(String f1) {
        // 截取年份部分
        String year = f1.substring(0, 4);
        // 截取月份部分
        String month = f1.substring(4, 6);
        // 截取日期部分
        String day = f1.substring(6, 8);
        // 去掉月份的前导零
        if (month.startsWith("0")) {
            month = month.substring(1);
        }
        // 去掉日期的前导零
        if (day.startsWith("0")) {
            day = day.substring(1);
        }
        // 拼接成所需的格式
        return  year + "/" + month + "/" + day+"/";
    }

   // @JmsListener(destination = "CAL1630_COIL_MES", containerFactory = "topicListenerContainer01")//


    //@JmsListener(destination = "C621_new_pdo", containerFactory = "topicListenerContainer01")//
    public void receiveTopic621(String message) {
        try {
            log.error("621");
            log.error(message);
            JSONObject key = JSONObject.parseObject(message).getJSONObject("key");
            String path = key.getString("path");
            String endtime = key.getString("endtime");
            String entid = key.getString("entid");
            String extid = key.getString("extid");


            // 构建查询条件
            Query query = new Query(Criteria.where("extid").is(extid));
            List<JDataSave621> jDataSave621List = mongoTemplate.find(query, JDataSave621.class);
            // jDataSave622List长度大于等于1的时候直接返回,反之执行方法
            if (jDataSave621List.size() >= 1) {
                return;
            } else {
                String fileName = extid + ".json.tar";
                TbBxFileSave tbBxFileSave = new TbBxFileSave();
                tbBxFileSave.setLine("C621");
                tbBxFileSave.setCoil_id(extid);
                tbBxFileSave.setMessage(message);
                tbBxFileSaveDao.insert(tbBxFileSave);

               // pdoUtils.calPdo621(extid, tbBxFileSave);
                sFtpUtils.calFile621(path, fileName, host621, tbBxFileSave);
            }
        } catch (JSchException e) {
            e.printStackTrace();
        }
    }

    //@JmsListener(destination = "C622_new_pdo", containerFactory = "topicListenerContainer02")
    public void receiveTopic622(String message) {
        try {
            log.error("622");
            log.error(message);
            JSONObject key = JSONObject.parseObject(message).getJSONObject("key");
            String path = key.getString("path");
            String endtime = key.getString("endtime");
            String entid = key.getString("entid");
            String extid = key.getString("extid");
            // 构建查询条件
            Query query = new Query(Criteria.where("extid").is(extid));
            List<JDataSave622> jDataSave622List = mongoTemplate.find(query, JDataSave622.class);
            // jDataSave622List长度大于等于1的时候直接返回,反之执行方法
            if (jDataSave622List.size() >= 1) {
                return;
            } else {
                String fileName = extid + ".json.tar";
                TbBxFileSave tbBxFileSave = new TbBxFileSave();
                tbBxFileSave.setLine("C622");
                tbBxFileSave.setCoil_id(extid);
                tbBxFileSave.setMessage(message);
                tbBxFileSaveDao.insert(tbBxFileSave);
                pdoUtils.calPdo622(extid, tbBxFileSave);
//                try {
//                    QueryWrapper<JColdPdo622> wrapper = new QueryWrapper<>();
//                    wrapper.eq("extid", extid);
//                    JColdPdo622 jColdPdo622 = jColdPdo622Daocs.selectOne(wrapper);
//                    LocalDateTime start_time = jColdPdo622.getProcess_start_time().toLocalDateTime();
//                    LocalDateTime end_time = jColdPdo622.getProcess_end_time().toLocalDateTime();
//                    LambdaQueryWrapper<TbDsjDataCollect> queryWrapper2 = new LambdaQueryWrapper<>();
//                    queryWrapper2.and(item -> item.eq(TbDsjDataCollect::getOut_data_source, "3.0").eq(TbDsjDataCollect::getProduction_line, "C622"));
//                    List<TbDsjDataCollect> tbDsjDataCollectList = tbDsjDataCollectDaocs.selectList(queryWrapper2);
//                    List<String> tbDsjDataCollectLists = new ArrayList<>();
//                    log.error("consunmer 中C622数据！extid：" + extid+";CollectList.size:"+tbDsjDataCollectList.size());
//                    for (TbDsjDataCollect tbDsjDataCollect : tbDsjDataCollectList) {
//                        tbDsjDataCollectLists.add(tbDsjDataCollect.getL1_variable_name());
//                    }
//                    int i3 = 0;
//                    HDDataConnection connect = sdkUtilscs.getConnect();
//                    ;
//                    while (!connect.isConnected()) {
//                        connect = sdkUtilscs.getConnect();
//                    }
//                    Map<String, Object> map = new HashMap<>();
//                    TbFalt tbFalt = new TbFalt();
//                    for (TbDsjDataCollect tbDsjDataCollect : tbDsjDataCollectList) {
//                        // 根据L1_variable_name去sdk查询tagID
//                        List<ImmutablePair<Integer, Integer>> tagIDsByTagNames = sdkUtilscs.findTagIDsByTagNames(tbDsjDataCollectLists, connect.getTagManager());
//                        List<HDRecord> hdRecordList = null;
////                        if (Duration.between(start_time, end_time).toMinutes() < 30) {
//// //根据tabID和tbDsjC622FlatPassTime表中的开始结束时间去查询sdk没条数据
////                            hdRecordList = sdkUtilscs.findMsgByIdAndTime(tagIDsByTagNames.get(i3).getLeft(), connect.getDataProvider(), start_time, end_time);
////
////                        } else {
//                        LocalDateTime pdoDataDate2 = end_time.minusMinutes(1);
//                        hdRecordList = sdkUtilscs.findMsgByIdAndTime(tagIDsByTagNames.get(i3).getLeft(), connect.getDataProvider(), pdoDataDate2, end_time);
////                        }
//                        if (hdRecordList.size() >0) {
//                            map.put(tbDsjDataCollect.getL1_variable_alias(), hdRecordList.get(0).getValueStr());
//                            tbFalt.setEdgeList(map);
//                        }
//                        i3++;
//                    }
//                    connect.dispose();
//                    tbFalt.setExtid(extid);
//                    tbFalt.setCreatetime(new Date());
//                    tbFaltMappercs.save(tbFalt);
//                } catch (Exception e) {
////                    try {
////                        connect.dispose();
////                    }
////                    catch( HDSdkException e1)
////                    {
////                    }
//                    e.printStackTrace();
//                    log.error("consunmer 中C622数据读取存在错误！extid：" + extid);
//                }
                sFtpUtils.calFile622(path, fileName, host, tbBxFileSave);

            }
        } catch (JSchException e) {
            e.printStackTrace();
        }
    }

    //@JmsListener(destination = "C642_new_pdo", containerFactory = "topicListenerContainer03")
    public void receiveTopic642(String message) {
        try {
            log.error("642");
            log.error("2130连退消息>>>" + message);
            JSONObject key = JSONObject.parseObject(message).getJSONObject("key");
            String path = key.getString("path");
            String endtime = key.getString("endtime");
            String entid = key.getString("entid");
            String extid = key.getString("extid");


            // 构建查询条件
            Query query = new Query(Criteria.where("extid").is(extid));
            List<JDataSave642> jDataSave642List = mongoTemplate.find(query, JDataSave642.class);
            // jDataSave642List长度大于等于1的时候直接返回,反之执行方法
            if (jDataSave642List.size() >= 1) {
                return;
            } else {
                String fileName = extid + ".json.tar";
                TbBxFileSave tbBxFileSave = new TbBxFileSave();
                tbBxFileSave.setLine("C642");
                tbBxFileSave.setCoil_id(extid);
                tbBxFileSave.setMessage(message);
                tbBxFileSaveDao.insert(tbBxFileSave);
                pdoUtils.calPdo642(extid, tbBxFileSave);
                sFtpUtils.calFile642(path, fileName, host642, tbBxFileSave);
            }
        } catch (JSchException e) {
            e.printStackTrace();
        }
    }

    public Boolean receiveTopic653(String message) {
        try {
            log.error("653");
            log.error("3#镀锌>>>" + message);
            JSONObject key = JSONObject.parseObject(message).getJSONObject("key");
            String path = key.getString("path");
            String endtime = key.getString("endtime");
            String entid = key.getString("entid");
            String extid = key.getString("extid");


            // 构建查询条件
            Query query = new Query(Criteria.where("extid").is(extid));
            List<JDataSave653> jDataSave653List = mongoTemplate.find(query, JDataSave653.class);
            // jDataSave653List长度大于等于1的时候直接返回,反之执行方法
            if (jDataSave653List.size() >= 1) {
                return false;
            } else {
                String fileName = extid + ".json.tar";
                TbBxFileSave tbBxFileSave = new TbBxFileSave();
                tbBxFileSave.setLine("C653");
                tbBxFileSave.setCoil_id(extid);
                tbBxFileSave.setMessage(message);
                tbBxFileSaveDao.insert(tbBxFileSave);
//                pdoUtils.calPdo653(extid,tbBxFileSave);
                return sFtpUtils.calFile653(path, fileName, host653, tbBxFileSave);
            }

        } catch (JSchException e) {
            //e.printStackTrace();
            return false;
        }
    }



    //@JmsListener(destination = "C621_new_pdi", containerFactory = "topicListenerContainer04")
    public void receiveTopicQMS621(String message) {
        try {
            log.info(message);
            JSONObject key = JSONObject.parseObject(message).getJSONObject("key");
            String entid = key.getString("entid");
          qmsService.readColdPdi(entid, "621");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //@JmsListener(destination = "C622_new_pdi", containerFactory = "topicListenerContainer05")
    public void receiveTopicQMS622(String message) {
        try {
            log.info(message);
            JSONObject key = JSONObject.parseObject(message).getJSONObject("key");
            String entid = key.getString("entid");
            qmsService.readColdPdi(entid, "622");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //@JmsListener(destination = "C642_new_pdi", containerFactory = "topicListenerContainer06")
    public void receiveTopicQMS642(String message) {
        try {
            log.info(message);
            JSONObject key = JSONObject.parseObject(message).getJSONObject("key");
            String entid = key.getString("entid");
            qmsService.readColdPdi(entid, "642");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //@JmsListener(destination = "C622_pdo_wt", containerFactory = "topicListenerContainer07")
    public void receiveTopicPDO622(String message) {
        try {
            log.error(message);
            JSONObject key = JSONObject.parseObject(message).getJSONObject("key");
            String extid = key.getString("extid");
            String weight = key.getString("weight");
            tbDsjRawcheckC642Service.updateWeight(extid, weight, "C622");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //@JmsListener(destination = "C621_pdo_wt", containerFactory = "topicListenerContainer08")
    public void receiveTopicPDO621(String message) {
        try {
            log.error(message);
            JSONObject key = JSONObject.parseObject(message).getJSONObject("key");
            String extid = key.getString("extid");
            String weight = key.getString("weight");
            tbDsjRawcheckC642Service.updateWeight(extid, weight, "C621");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //@JmsListener(destination = "C642_pdo_wt", containerFactory = "topicListenerContainer09")
    public void receiveTopicPDO642(String message) {
        try {
            log.error(message);
            JSONObject key = JSONObject.parseObject(message).getJSONObject("key");
            String extid = key.getString("extid");
            String weight = key.getString("weight");
            tbDsjRawcheckC642Service.updateWeight(extid, weight, "C642");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
     //刷mong曲线到新表
    public void test1() throws SftpException, IOException, JSchException {

      // String path = "/data/dsc/RCL2150/2025/3/25/";
      // String fileName = "53W320640200" + ".json.tar";
        QueryWrapper<TbBxFileSave> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TbBxFileSave::getLine, "TCM2280");
       List<TbBxFileSave>  aa =  tbBxFileSaveDao.selectList(wrapper);
        for (TbBxFileSave entiy : aa) {

         String   message=entiy.getMessage();


     /* String  message="{\n" +
            "     \"endtime\" : \"20250414033507\",\n" +
            "      \"entId\": \"D250411501T\",\n" +
            "      \"extId\": \"54B385260000\"\n" +
        "}";*/
/*
        String  message="{\n" +
                "     \"endtime\" : \"20250412162007\",\n" +
                "      \"entId\": \"D250411501T\",\n" +
                "      \"extId\": \"54W374420000\"\n" +
                "}";*/
        try {
            log.info("本钢TCM2280");
            log.info(message);
            // JSONObject key = JSONObject.parseObject(message).getJSONObject("key");
            JSONObject key = JSONObject.parseObject(message);
            String extid = key.getString("extId");
            String bao_time=key.getString("endtime");
            String f2 = transform(bao_time);
            String path ="/data/dsc/TCM2280/"+f2;

            // String endtime = key.getString("endtime");
            // String entid = key.getString("entid");
            // String extid = key.getString("extid");


            // 构建查询条件
            Query query = new Query(Criteria.where("extid").is(extid));
            List<JDataSavemong2280_1> jDataSave2280List = mongoTemplate.find(query, JDataSavemong2280_1.class);
            // jDataSave622List长度大于等于1的时候直接返回,反之执行方法
            if (jDataSave2280List.size() >= 1) {
                continue;
            } else {
                String fileName = extid + ".json.tar";
                TbBxFileSave tbBxFileSave = new TbBxFileSave();
                tbBxFileSave.setLine("TCM2280");
                tbBxFileSave.setCoil_id(extid);
                tbBxFileSave.setMessage(message);
                tbBxFileSaveDao.insert(tbBxFileSave);

                sFtpUtils.calFile2280(path, fileName, host, tbBxFileSave);
            }
        } catch (JSchException e) {
            log.error(e.getMessage(),e);
        }

        }
    }
    public void test() throws SftpException, IOException, JSchException {

        // String path = "/data/dsc/RCL2150/2025/3/25/";
        // String fileName = "53W320640200" + ".json.tar";

        QueryWrapper<TbBxFileSave> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TbBxFileSave::getLine, "CAL1630");
        wrapper.lambda().eq(TbBxFileSave::getStatusftp, 1d);
        List<TbBxFileSave>  aa =  tbBxFileSaveDao.selectList(wrapper);
        for (TbBxFileSave entiy : aa) {

            String message = entiy.getMessage();
           /* String message = "{\n" +
                    "     \"endtime\" : \"20250414190809\",\n" +
                    "      \"entId\": \"54H364700000\",\n" +
                    "      \"extId\": \"54H364700000\"\n" +
                    "}";*/
/*
        String  message="{\n" +
                "     \"endtime\" : \"20250412162007\",\n" +
                "      \"entId\": \"D250411501T\",\n" +
                "      \"extId\": \"54W374420000\"\n" +
                "}";*/
            try {
                log.info("CAL1630");
                log.info(message);
                // JSONObject key = JSONObject.parseObject(message).getJSONObject("key");
                JSONObject key = JSONObject.parseObject(message);
                String extid = key.getString("extId");
                String bao_time = key.getString("endtime");
                String f2 = transform(bao_time);
                String path = "/data/dsc/CAL1630/" + f2;

                // String endtime = key.getString("endtime");
                // String entid = key.getString("entid");
                // String extid = key.getString("extid");


                // 构建查询条件
                Query query = new Query(Criteria.where("extid").is(extid));
                List<JDataSavemong1630> jDataSave2280List = mongoTemplate.find(query, JDataSavemong1630.class);
                // jDataSave622List长度大于等于1的时候直接返回,反之执行方法
                if (jDataSave2280List.size() >= 1) {
                    continue;
                } else {
                    String fileName = extid + ".json.tar";
                    TbBxFileSave tbBxFileSave = new TbBxFileSave();
                    tbBxFileSave.setLine("CAL1630");
                    tbBxFileSave.setCoil_id(extid);
                    tbBxFileSave.setMessage(message);
                    //tbBxFileSaveDao.insert(tbBxFileSave);

                    sFtpUtils.calFile1630_TEST(path, fileName, host, tbBxFileSave);
                }
            } catch (JSchException e) {
                log.error(e.getMessage(), e);
            }
        }

    }

}
